#include "TcpServer.hpp"
#include "ServerCal.hpp"
#include "log.hpp"

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string server_ip = argv[1]; // 服务器IP地址
    uint16_t server_port = stoi(argv[2]); // 服务器端口号

    Sockets socket_;
    socket_.Socket(); // 创建TCP套接字
    if(!socket_.Connet(server_ip, server_port)) 
    {
        std::cerr << "Connect error: " << strerror(errno) << std::endl;
        return 1;
    }

    srand(time(nullptr) ^ getpid());
    int cnt = 1;
    const std::string opers = "+-*/%=-=&^";
    std::string inbuffer_stream;

    while(cnt <= 10)
    {
        std::cout << "=================第" << cnt << "次测试....., " << "===============" << std::endl;
        int x = rand() % 100 + 1;
        usleep(1234);
        int y = rand() % 100;
        usleep(4321);
        char oper = opers[rand()%opers.size()];
        Request req(x, y, oper);
        req.DebugPrint();

        std::string package;
        req.Serialize(package);

        package = Encode(package);

        write(socket_.GetSocket(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: " << n << "\n" << package;
        // n = write(sockfd.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;
        // n = write(sockfd.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;
        // n = write(sockfd.Fd(), package.c_str(), package.size());
        // std::cout << "这是最新的发出去的请求: \n" << n << "\n" << package;


        char buffer[4096];
        ssize_t n = read(socket_.GetSocket(), buffer, sizeof(buffer)); // 我们也无法保证我们能读到一个完整的报文
        if(n > 0)
        {
            buffer[n] = '\0';
            inbuffer_stream += buffer; // "len"\n"result code"\n
            std::cout << inbuffer_stream << std::endl;
            std::string content;
            bool r = Decode(inbuffer_stream, content); // "result code"
            assert(r);

            Response resp;
            r = resp.Deserialize(content);
            assert(r);

            resp.DebugPrint();
        }

        std::cout << "=================================================" << std::endl;
        sleep(1);

        cnt++;
    }
    socket_.Close(); // 关闭套接字

    return 0;
}